package com.unitd.frame.sso.web.filter;

import com.unitd.frame.sso.common.config.SSOConfig;
import com.unitd.frame.sso.common.helper.SSOHelper;
import com.unitd.frame.sso.common.token.Token;
import com.unitd.frame.comm.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @desc SSO 过滤器验证登录状态、权限过滤
 * @filename SSOFilter.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/10/18
 */
public class SSOFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(SSOFilter.class.getName());
	private static String OVERURL = null;

	@Override
	public void init(FilterConfig config) throws ServletException {

		// 从应用 web.xml 配置参数中; 获取不需要拦截的URL
		OVERURL = config.getInitParameter("over.url");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		// 判断当前请求是否为过滤器忽略的请求
		boolean isOver = HttpUtils.inContainURL(req, OVERURL);

		// 不需要拦截的URL, 进行安全校验Cookie
		if (!isOver) {
			// 获取当前请求的Token
			Token token = SSOHelper.getToken(req);
			if (token == null) {
				logger.info("当前请求URL为:" + req.getRequestURL());
				// 退出重定向登录页,跳至 sso.properties 配置的属性 sso.login.url 地址
				SSOHelper.clearRedirectLogin(req, res);
				return;
			} else {
				req.setAttribute(SSOConfig.SSO_TOKEN_ATTR, token);
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		OVERURL = null;
	}
}